<template>
	<view class="basic-dy-parse tn-safe-area-inset-bottom">
		<!-- 页面内容 -->
		<view class="video-form">
			<view class="video-input">
				<view class="video-input-text">
					<tn-input v-model="dyVidwoUrl" placeholder="长按粘贴分享信息" :type="'textarea'" :maxHeight="240"
						:border="true" :clearable="false" :autoHeight="false" />
				</view>
				<view class="video-submit">
					<view class="button-group">
						<tn-button :shadow="true" :plain="true" class="btn" height="100rpx"
							@click="getClip">粘贴</tn-button>
						<tn-button :shadow="true" :plain="true" class="btn" height="100rpx"
							@click="cleanAll">清空</tn-button>
					</view>
					<view class="button-group">
						<tn-button :shadow="true" class="btn" height="100rpx" backgroundColor="#01BEFF"
							fontColor="#FFFFFF" @click="parseUrl">解析</tn-button>
					</view>
				</view>
			</view>

			<view class="video-result">
				<view class="video-img-div">
					<image class="video-image" :src="videoResult.image" mode="aspectFit"></image>
				</view>
				<view class="video-info" v-if="isParse">
					<view class="video-info-item">
						<view class="item-text-title">
							标题：{{videoResult.title}}
						</view>
						<tn-button shape="icon" @click="copyText(videoResult.title)"><text
								class="tn-icon-copy"></text></tn-button>
					</view>
					<view class="video-info-item">
						<view class="item-text">
							封面：{{videoResult.image}}
						</view>
						<tn-button shape="icon" @click="copyText(videoResult.image)"><text
								class="tn-icon-copy"></text></tn-button>
					</view>
					<view class="video-info-item">
						<view class="item-text">
							地址：{{videoResult.video}}
						</view>
						<tn-button shape="icon" ><text class="tn-icon-copy" @click="copyText(videoResult.video)" ></text></tn-button>
					</view>
					<view v-if="shortUrl!=''" class="video-info-item">
						<view class="item-text">
							短链：{{shortUrl}}
						</view>
						<tn-button shape="icon" @click="copyText(shortUrl)"><text
								class="tn-icon-copy"></text></tn-button>
					</view>					
					<view style="margin-top:10rpx ;">
						<tn-button style="margin-right: 10rpx;" :shadow="true" :plain="true" class="btn" height="70rpx"
							@click="copyJson">复制地址</tn-button>
						<tn-button style="margin-right: 10rpx;" :shadow="true" :plain="true" class="btn" height="70rpx"
							@click="downLoadVideo">下载视频</tn-button>	
						<tn-button :shadow="true" :plain="true" class="btn" height="70rpx"
							@click="getShortVideo">获取短链</tn-button>	
					</view>
				</view>
			</view>
			<view class="bottom-text">
				视频归平台及作者所有，本应用不储存任何视频图片
			</view>
		</view>
		<tn-modal v-model="downloadShow" :custom="true" :maskCloseable="false">
			<view class="custom-modal-content">
				<view class="tn-icon tn-icon-about-fill">正在下载中</view>
				<view class="text" style="margin-top: 20rpx;">
					<tn-line-progress :percent="progress" activeColor="#01BEFF"></tn-line-progress>
				</view>
			</view>
		</tn-modal>
		<tn-modal v-model="showAdDlg" :content="adMsg" :button="button" :maskCloseable="false" @click="onClickBtn" ></tn-modal>		
	</view>
</template>

<script>
	export default {
		name: 'dyParse',
		components: {},
		data() {
			return {
				dyVidwoUrl: "",
				videoResult: {
					video: "",
					image: "",
					title: ""
				},
				regexpStr: /[a-zA-Z]+:\/\/[^\s]*/g,
				isParse: false,
				downloadShow: false,
				progress: 0,
				shortUrl:"",
				rewardedVideoAd:null,
				isSendGift:false,
				showAdDlg:false,
				adMsg:"您将观看一段广告，来获取资源权限",
				button: [{
					text: '取消',
					backgroundColor: '#E6E6E6',
					plain: true,
				  },
				  {
					text: '播放',
					backgroundColor: 'tn-bg-indigo',
					fontColor: '#FFFFFF'
				  }
				]
			}
		},
		onLoad() {
		  this.isSendGift=false;
		  this.rewardedVideoAd = uni.createRewardedVideoAd({ adUnitId: 'adunit-c849be5752274263' })
		  this.rewardedVideoAd.onLoad(() => {
			console.log('激励视频 广告加载成功')
		  })
		  this.rewardedVideoAd.onError((err) => {
			  uni.showToast({
			  	title: '视频加载失败，请重新获取',
			  	duration: 2000
			  })
		  })
		  this.rewardedVideoAd.onClose((res) => {
			// 用户点击了【关闭广告】按钮
			if (res && res.isEnded) {
			   this.isSendGift = true
			   uni.showToast({
			   	title: '已经获取奖励',
			   	duration: 2000
			   })
			} else {
				uni.showToast({
					title: '请完整观看视频，获取奖励',
					duration: 2000
				})
			  // 播放中途退出，不下发游戏奖励
			}
		  })
		},
		methods: {
			onClickBtn(opt){
				if (opt.index == 1){
					this.showAd()
				}
				this.showAdDlg=false;
			},
			openAdDlg(){
				this.showAdDlg = true;
			},
			copyText(text) {
				// if (!this.isSendGift){
				// 	this.openAdDlg()
				// 	return 
				// }
				if (text == "") {
					return
				}
				uni.setClipboardData({
					data: text,
					success: function() {
						uni.showToast({
							title: '已复制到剪切板',
							duration: 2000
						})
					}
				})
			},
			copyJson() {
				this.copyText(this.videoResult.video)
			},
			showAd(){
				let that = this
				this.rewardedVideoAd.show().then(() => {
						console.log('激励视频 广告显示');
					})
			},
			
			downLoadVideo() {
				
				// if (!this.isSendGift){
				// 	this.openAdDlg()
				// 	return 
				// }
				
				this.downloadShow = true
				this.progress = 0
				let that = this
				let downloadUrl="https://auth.bogerj.cn/api/downloadVideo?key="+this.videoResult.id
				const downloadTask = uni.downloadFile({
					url: downloadUrl, //仅为示例，并非真实的资源
					timeout:1800*1000,
					success: (res) => {
						console.log(res)
						if (res.statusCode === 200) {
							that.saveFile(res,this.videoResult)
							console.log('下载成功');
						} else {
							console.log('下载成功.........');
						}
						that.downloadShow = false
					},
					fail: (err) => {
						console.log(err);
						uni.showToast({
							title: err.errMsg,
						})
						that.downloadShow = false
					}
				});

				downloadTask.onProgressUpdate((res) => {
					that.progress = res.progress
				});
			},
			saveFile(res,videoInfo) {
				
				uni.saveVideoToPhotosAlbum({
				  filePath: res.tempFilePath,
				  success:function(){
					uni.hideLoading()
					uni.showToast({title:"保存到相册成功"})
				  },
					fail: function(err) {
						uni.showToast({
							title: '文件保存失败:'+err.errMsg,
							duration: 2000
						})
						console.log(err);
					}				  
				})
			},
			openUrl(){
				uni.openUrl({
					url: this.videoResult.video
				})
				// uni.navigateTo({ url: 'plugin://NativePlugin/webview?url='+this.videoResult.video })
			},
			// 获取短链接
			getShortVideo(){
				
				// if (!this.isSendGift){
				// 	this.openAdDlg()
				// 	return 
				// }
				
				if (this.videoResult.video==""){
					uni.showToast({
						title: "没有需要转换的链接",
						duration: 2000
					})
					return 
				}
				
				let openId = uni.getStorageSync("openid")
				let param= {
					userName:openId,
					realUrl:this.videoResult.video
				}
				this.$api.getShortUrl(param,res=>{
					if (res.code == 200) {
						this.shortUrl = res.data
					} else {
						this.$common.errorToShow(res.msg)
					}
				})
			},
			cleanAll() {
				this.dyVidwoUrl = "";
				this.videoResult = {
					video: "",
					image: "",
					title: ""
				}
				this.isParse = false
			},
			getClip() {
				let that = this
				uni.getClipboardData({
					success: function(res) {
						console.log(res)
						that.dyVidwoUrl = res.data;

					}
				});
			},
			parseUrl() {
				if (this.dyVidwoUrl == "") {
					this.$common.errorToShow("请输入分享的链接")
					return
				}
				
				// 取正则
				let dyShareInfo = ""
				let dyUrl = this.dyVidwoUrl.match(this.regexpStr)
				if (dyUrl && dyUrl != null) {
					dyShareInfo = dyUrl[0]
				}
				
				let openId = uni.getStorageSync("openid")
				let param = "key="+openId+"&url=" + dyShareInfo
				this.$api.parseDyVideo({
					param: param
				}, (res) => {
					console.log(res)
					if (res.code == 200) {
						this.videoResult = res.data
						this.isSendGift=false;
						this.isParse = true
					} else {
						this.$common.errorToShow(res.msg)
						this.isParse = false
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.basic-dy-parse {
		background-color: $tn-bg-gray-color;
		height: 100vh;
	}

	.video-form {
		box-sizing: border-box;
		padding: 10rpx;

		.video-input {
			display: flex;
			padding: 10rpx 20rpx;
			background-color: #fff;
			border-radius: 8rpx;
			margin-bottom: 10rpx;

			.video-input-text {
				flex: 1;
			}
		}

		.video-submit {
			.button-group {
				margin-bottom: 10rpx;
			}
			.btn {
				margin: 5px 2px;
			}
		}

		.video-result {
			padding: 20rpx;
			background-color: #fff;
			border-radius: 8rpx;
			margin-bottom: 20rpx;

			.video-img-div {
				width: 100%;
				height: 200px;
				background-color: #080808;
				text-align: center;
			}

			.video-image {
				height: 200px;
			}

			.video-info {
				padding-top: 20px;

				.video-info-item {
					width: 100%;
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-size: 28rpx;

					.item-text {
						flex: 1;
						text-overflow: ellipsis;
						overflow: hidden;
						white-space: nowrap;
					}
				}

			}
		}

		.bottom-text {
			text-align: center;
			font-size: 28rpx;
		}
	}
</style>